<template>
    <div style="width: 100%;height:100%">
        <rx-fullcalendar
            v-if="options.header"
            ref="calendarView"
            :options="options"
            @changeDay="changeDay"
            @changeWeakDays="changeWeakDays"
            @changeMonth="changeMonth"
            @handButtonClick="handButtonClick"
        >
        </rx-fullcalendar>
    </div>

</template>

<script>
import {Util} from "@lowcode/jpaas-base-lib"
import {PublicFunction} from "@lowcode/jpaas-share-component";
import CalendarViewFunc from "./CalendarViewFunc.js";
import FormCalendarViewApi from '@/common/api/form/formCalendarView.js';
import {mapState} from 'pinia';
import useMain from "@/stores/useMain.js";
import userUser from "@/stores/userUser.js";

export default {
    name: "FormCalendarViewShow",
    props:["calendarKey","params","menuParams"],
    mixins:[CalendarViewFunc,PublicFunction],
    data() {
        return {
            idField:"",
            calendarView:{},
            //所有查询到的数据
            calendarData:{},
            options: {
                header: "",
                firstDay: 1,
                locale: "zh-cn",
                dayTableHeaders: [],
                weeksTableHeaders: [],
                dayData: [],
                weekData: [],
                monthData: [],
                buttons:[],
                timeQuantum:false
            },
            params_:{},
            //权限字段
            pmtFields:[],
            calendarId:"",
            canEditCalendarView:false
        }
    },
    computed: {
        ...mapState(useMain, ['appId','appKey','buttons','allButtons']),
        ...mapState(userUser, ['user'])
    },
    created() {
        this.initParams();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"FormCalendarView",key);
        },
        /**
         * 初始化参数
         */
        initParams() {
            //通过弹窗打开 Util.open
            if (this.calendarKey) {
                this.loadData(this.calendarKey);
            }
            //从弹窗打开 DialogView
            else if (this.menuParams) {
                this.handParams(JSON.parse(this.menuParams),{});
            }
            //使用路由打开
            else {
                this.curMenuId=this.$route.meta.id;
                let params=this.$route.meta.params || this.$route.params;
                this.handParams(params,this.$route.query || {});
            }
        },
        handParams(params,query,key) {
            let params_;
            if (typeof params == 'string') {
                params_ = JSON.parse(params);
            } else {
                params_ = params;
            }
            let _key = key ? key.substring(0, key.lastIndexOf('_Calendar')) : ""
            let calendarKey = params_.calendarKey || _key;
            delete  params_.calendarKey;
            if (params_.query) {
                Object.assign(params_.query,query);
            }
            this.params_=params_;
            this.loadData(calendarKey,params_);
        },
        loadData(calendarKey,parameter,callback){
            let params=parameter?{params:JSON.stringify(parameter)}:{};
            FormCalendarViewApi.getDataByKey(calendarKey,this.curMenuId,params).then(res=>{
                if(res.success && res.data && res.data.calendarView){
                    this.hasRightEditForm(res.data);
                    if(callback){
                        callback(res.data);
                        return;
                    }
                    this.calendarView=res.data.calendarView;
                    this.calendarData=res.data.calendarData;
                    if(res.data.formBoPmt){
                        this.pmtFields=res.data.formBoPmt.fields?JSON.parse(res.data.formBoPmt.fields):[];
                    }
                    this.initOptions();
                }else {
                    this.$message.error(this.i18n('loadDataTips1','未查询到key为')+calendarKey+this.i18n('loadDataTips2','的日历视图!'));
                }
            })
        },
        /**
         * 新增编辑按钮
         */
        addOption(){
            if(this.calendarView){
                //按钮
                if(this.calendarView.buttonConf){
                    let button={
                        btnClick:"editCalendar",
                        btnLabel:this.i18n('list.editCalendar','设计日历视图'),
                        btnName:"aa_editCalendar",
                        btnType:"head",
                        idx_:"ajsvahp909455",
                        isDefault:true,
                        isLeaf:true,
                        serial:0
                    }
                    this.options.buttons.unshift(button);
                }
            }
        },
        hasRightEditForm(data){
            if(!data.calendarView || !data.calendarView.id){
                return;
            }
            this.calendarId=data.calendarView.id;
            let self_=this;
            let parma={
                appId:this.appId,
                params:{
                    formCalendarView:this.calendarId
                }
            }
            FormCalendarViewApi.checkCanChange(parma).then(res=>{
                if(res && res.formCalendarView){
                    self_.canEditCalendarView=res.formCalendarView;
                    self_.addOption();
                }
            });
        },
        /**
         * 初始化options
         */
        initOptions(){
            if(this.calendarView){
                //按钮
                if(this.calendarView.buttonConf){
                    this.options.buttons=this.initButton(this.calendarView.buttonConf);
                }
                //日历视图
                if(this.calendarView.columnConf){
                    this.idField=this.calendarView.columnConf.idField;
                    this.initView(this.calendarView.columnConf);
                }
                if(this.calendarView.jsScript){
                    this.initJsScript(this.calendarView.jsScript);
                }
            }
        },
        //初始化视图
        initView(columnConf){
            let self=this;
            let header=[];
            this.options.timeQuantum= columnConf.timeQuantum?columnConf.timeQuantum:false;
            //月视图
            if(columnConf.monthConf && columnConf.monthConf.show){
                header.push("month");
                //获取数据
                this.options.monthData=this.getMonthData(this.calendarData.monthData,columnConf);
            }
            //周视图
            if(columnConf.weekConf && columnConf.weekConf.show){
                header.push("week");
                if(columnConf.weekConf.weekColumns && columnConf.weekConf.weekColumns.length>0){
                    let weeksTableHeaders=[];
                    columnConf.weekConf.weekColumns.find(function(item){
                        if(self.pmtFields && self.pmtFields.length>0){
                            let field=self.pmtFields.find(function(obj){
                                if(item.fieldKey==obj.field){
                                    return true;
                                }
                                return false;
                            });
                            if(field){
                                weeksTableHeaders.push({
                                    title:item.fieldName,
                                    key:item.fieldKey,
                                })
                            }
                        }else {
                            weeksTableHeaders.push({
                                title:item.fieldName,
                                key:item.fieldKey,
                            })
                        }
                    });
                    this.options.weeksTableHeaders= weeksTableHeaders;
                }
                this.options.weekData=this.getWeekData(this.calendarData.weekData,columnConf)
            }
            //日视图
            if(columnConf.dayConf && columnConf.dayConf.show){
                header.push("day");
                if(columnConf.dayConf.dayColumns && columnConf.dayConf.dayColumns.length>0){
                    let dayTableHeaders=[];
                    columnConf.dayConf.dayColumns.find(function(item){
                        if(self.pmtFields && self.pmtFields.length>0){
                            let field=self.pmtFields.find(function(obj){
                                if(item.fieldKey==obj.field){
                                    return true;
                                }
                                return false;
                            });
                            if(field){
                                dayTableHeaders.push({
                                    title:item.fieldName,
                                    key:item.fieldKey,
                                })
                            }
                        }else {
                            dayTableHeaders.push({
                                title:item.fieldName,
                                key:item.fieldKey,
                            })
                        }
                    });
                    this.options.dayTableHeaders= dayTableHeaders;
                }
                this.options.dayData=this.getDayData(this.calendarData.dayData,columnConf);
            }
            if(header.length>0){
                this.options.header=header.join(",");
            }
        },
        /*月数据
         {
               pkId:"主键",
               title: "睡觉",
               start: "2022-05-08",
               end: "2022-05-10",
               cssClass: ["family", "career"],
               YOUR_DATA: {}
          }*/
        getMonthData(data,columnConf){
            let monthData=[];
            if(data){
                let timeFields=[];
                if(columnConf.timeFields){
                    timeFields=columnConf.timeFields
                }else {
                    timeFields=[{
                        startField:columnConf.startField,
                        endField:columnConf.endField,
                        background:"",
                    }];
                }
                for (let i = 0; i < timeFields.length; i++) {
                    let timeField=timeFields[i];
                    for (let j = 0; j < data.length; j++) {
                        let item = data[j];
                        let obj={
                            pkId:item[this.idField],
                            title: item.monthTitle,
                            start: item[timeField.startField],
                            cssClass: ["family", "career"],
                            YOUR_DATA: {},
                            background:timeField.background
                        }
                        if(columnConf.timeQuantum){
                            obj.end=item[timeField.endField]
                        }
                        if(obj.start){
                            monthData.push(obj);
                        }
                    }
                }
            }
            return monthData;
        },
        /*周数据
            {
               pkId:"主键",
               start: "2022-05-08",
               end: "2022-05-10",
               number1: "000015",
            }*/
        getWeekData(data,columnConf){
            let weekConf=columnConf.weekConf;
            let weekData=[];
            if(data){
                let timeFields=[];
                if(columnConf.timeFields){
                    timeFields=columnConf.timeFields;
                }else {
                    timeFields=[{
                        startField:columnConf.startField,
                        endField:columnConf.endField,
                        background:"",
                    }];
                }
                for (let i = 0; i < timeFields.length; i++) {
                    let timeField=timeFields[i];
                    for (let j = 0; j < data.length; j++) {
                        let item = data[j];
                        let obj={
                            pkId:item[this.idField],
                            start: item[timeField.startField],
                        }
                        if(columnConf.timeQuantum){
                            obj.end=item[timeField.endField]
                        }else {
                            //没有结束时间就选当天结束时间等于开始时间
                            obj.end=item[timeField.startField]
                        }
                        if(timeField.background){
                            obj.background = timeField.background
                        }else {
                            obj.background = '#02c5b7'
                        }
                        for (let j = 0; j < weekConf.weekColumns.length; j++) {
                            let column=weekConf.weekColumns[j];
                            obj[column.fieldKey]=item[column.fieldKey];
                        }
                        if(obj.start){
                            weekData.push(obj);
                        }
                    }
                }
            }
            return weekData;
        },
        /*天数据
            {
               pkId:"主键",
               start: "2022-05-08",
               end: "2022-05-09",
               number1: "000015",
         }*/
        getDayData(data,columnConf){
            let dayConf=columnConf.dayConf;
            let dayData=[];
            if(data){
                let timeFields=[];
                if(columnConf.timeFields){
                    timeFields=columnConf.timeFields
                }else {
                    timeFields=[{
                        startField:columnConf.startField,
                        endField:columnConf.endField,
                        background:"",
                    }];
                }
                for (let i = 0; i < timeFields.length; i++) {
                    let timeField=timeFields[i];
                    for (let j = 0; j < data.length; j++) {
                        let item = data[j];
                        let obj={
                            pkId:item[this.idField],
                            start: item[timeField.startField],
                        }
                        if(columnConf.timeQuantum){
                            obj.end=item[timeField.endField]
                        }
                        if(timeField.background){
                            obj.background = timeField.background
                        }else {
                            obj.background = '#02c5b7'
                        }
                        for (let j = 0; j < dayConf.dayColumns.length; j++) {
                            let column=dayConf.dayColumns[j];
                            obj[column.fieldKey]=item[column.fieldKey];
                        }
                        if(obj.start){
                            dayData.push(obj);
                        }
                    }
                }
            }
            return dayData;
        },
        changeDay(day) {
            let self=this;
            this.loadData(this.calendarView.key,{day:day},function (data){
                self.calendarData.dayData=data.calendarData.dayData;
                self.options.dayData=self.getDayData(self.calendarData.dayData,self.calendarView.columnConf);
            });
        },
        changeWeakDays(weeks) {
            let self=this;
            this.loadData(this.calendarView.key,{weeks:weeks},function (data){
                self.calendarData.weekData=data.calendarData.weekData;
                self.options.weekData=self.getWeekData(self.calendarData.weekData,self.calendarView.columnConf);
            });
        },
        changeMonth(start, end) {
            let self=this;
            let months=[start,end];
            this.loadData(this.calendarView.key,{months:months},function (data){
                self.calendarData.monthData=data.calendarData.monthData;
                self.options.monthData=self.getMonthData(self.calendarData.monthData,self.calendarView.columnConf);
            });
        },
        initJsScript(jsScript){
            if (jsScript) {
                jsScript=Util.replaceDefault(jsScript);
                let func=new Function("return " + jsScript);
                jsScript=func();
                //定义数据
                for(let key in jsScript.data()){
                    let value=jsScript.data()[key];
                    //设置双向绑定值
                    Vue.util.defineReactive(this,key,value);
                }
                //定义方法
                for(let method in jsScript.methods){
                    this[method]=jsScript.methods[method];
                }
                //定义监听
                for(let watch in jsScript.watch){
                    let json=jsScript.watch[watch];
                    if(typeof json == "function"){
                        this.$watch(watch, json);
                    }else{
                        let handler=json.handler;
                        delete json.handler;
                        this.$watch(watch, handler,json);
                    }
                }
                //加载方法
                jsScript.created.apply(this);
            }
        },
        //处理按钮
        handButtonClick(data,button){
            data=data?data:{};
            if(!button) return;
            this[button.btnClick](data);
        },
        //初始化按钮
        initButton(buttons){
            if (this.user && this.user.admin) {
                return buttons;
            }
            let buttonKeys = this.buttons[this.appKey];
            //未配置菜单按钮 或 当前日历视图无按钮 则直接返回
            if(!buttonKeys || buttonKeys.length==0 || !buttons || buttons.length==0){
                return  buttons;
            }
            let newButtons=[];
            //先获取当前应用下的按钮，计算权限
            for (let i = 0; i < buttonKeys.length; i++) {
                for (let j = 0; j < buttons.length; j++) {
                    if(buttonKeys[i] == buttons[j].btnName){
                        newButtons.push(buttons[j]);
                        break;
                    }
                }
            }
            //计算全部按钮的权限，如未查到则当前未对按钮做资源授权，返回视图全部按钮
            if(newButtons.length==0){
                let allButtons=Object.values(this.allButtons);
                if(!allButtons || allButtons.length==0){
                    return  buttons;
                }
                //将所有按钮放到当前数组中
                let allBtns=[];
                for (let i = 0; i < allButtons.length; i++) {
                    allBtns.push(...allButtons[i]);
                }
                for (let i = 0; i < buttons.length; i++) {
                    let button=buttons[i];
                    let show=false;
                    for (let j = 0; j < allBtns.length; j++) {
                        if(button.btnName==allBtns[j]){
                            show=true;
                            break;
                        }
                    }
                    if(!show){
                        newButtons.push(button);
                    }
                }
            }
            return  newButtons;
        }

    },
    watch: {},
}
</script>

<style scoped>

</style>
